import React, { useState, useCallback } from 'react';
import {
  Container,
  Paper,
  Typography,
  Box,
  Stepper,
  Step,
  StepLabel,
  Button,
  Alert,
  Snackbar,
} from '@mui/material';
import { ArrowBack } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useContent } from '../../hooks';
import { ContentType, CreateContentRequest } from '../../types';
import { 
  ContentTypeSelector,
  ContentInfoForm,
  MediaUploader,
  CreateSummary 
} from './components';

const steps = ['选择类型', '基本信息', '上传媒体', '确认创建'];

interface CreateData {
  contentType: ContentType;
  title: string;
  textContent: string;
  cover?: File;
  images?: File[];
  video?: File;
}

const Create: React.FC = () => {
  const navigate = useNavigate();
  const { createContent, loading } = useContent();
  
  const [activeStep, setActiveStep] = useState(0);
  const [createData, setCreateData] = useState<CreateData>({
    contentType: ContentType.IMAGE,
    title: '',
    textContent: '',
  });
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'success' as 'success' | 'error' | 'warning' | 'info',
  });

  // 下一步
  const handleNext = useCallback(() => {
    setActiveStep((prevStep) => prevStep + 1);
  }, []);

  // 上一步
  const handleBack = useCallback(() => {
    setActiveStep((prevStep) => prevStep - 1);
  }, []);

  // 更新创建数据
  const updateCreateData = useCallback((data: Partial<CreateData>) => {
    setCreateData(prev => ({ ...prev, ...data }));
  }, []);

  // 验证当前步骤
  const validateStep = useCallback((step: number): boolean => {
    switch (step) {
      case 0: // 选择类型
        return !!createData.contentType;
      case 1: // 基本信息
        return !!(createData.title.trim() && createData.textContent.trim());
      case 2: // 上传媒体
        if (createData.contentType === ContentType.IMAGE) {
          return !!(createData.images && createData.images.length > 0);
        } else {
          return !!createData.video;
        }
      default:
        return true;
    }
  }, [createData]);

  // 提交创建
  const handleSubmit = useCallback(async () => {
    try {
      const requestData: CreateContentRequest = {
        contentType: createData.contentType,
        title: createData.title,
        textContent: createData.textContent,
        cover: createData.cover,
        images: createData.images,
        video: createData.video,
      };

      await createContent(requestData);
      
      setSnackbar({
        open: true,
        message: '内容创建成功！',
        severity: 'success',
      });

      // 延迟跳转到我的内容页面
      setTimeout(() => {
        navigate('/my-contents');
      }, 1500);
    } catch (error) {
      setSnackbar({
        open: true,
        message: error instanceof Error ? error.message : '创建失败',
        severity: 'error',
      });
    }
  }, [createData, createContent, navigate]);

  // 渲染步骤内容
  const renderStepContent = (step: number) => {
    switch (step) {
      case 0:
                 return (
           <ContentTypeSelector
             value={createData.contentType}
             onChange={(contentType: ContentType) => updateCreateData({ contentType })}
           />
         );
       case 1:
         return (
           <ContentInfoForm
             title={createData.title}
             textContent={createData.textContent}
             onChange={(data: { title?: string; textContent?: string }) => updateCreateData(data)}
           />
         );
       case 2:
         return (
           <MediaUploader
             contentType={createData.contentType}
             cover={createData.cover}
             images={createData.images}
             video={createData.video}
             onChange={(data: { cover?: File; images?: File[]; video?: File }) => updateCreateData(data)}
           />
         );
      case 3:
        return (
          <CreateSummary
            data={createData}
          />
        );
      default:
        return null;
    }
  };

  return (
    <Container maxWidth="md" sx={{ py: 4 }}>
      {/* 返回按钮 */}
      <Box sx={{ mb: 3 }}>
        <Button
          startIcon={<ArrowBack />}
          onClick={() => navigate(-1)}
          sx={{ color: 'text.secondary' }}
        >
          返回
        </Button>
      </Box>

      <Paper elevation={3} sx={{ p: 4 }}>
        {/* 标题 */}
        <Typography 
          variant="h4" 
          component="h1" 
          gutterBottom
          sx={{ 
            fontWeight: 700,
            background: 'linear-gradient(45deg, #2196f3 30%, #21cbf3 90%)',
            backgroundClip: 'text',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            textAlign: 'center',
            mb: 4
          }}
        >
          创建内容
        </Typography>

        {/* 步骤指示器 */}
        <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
          {steps.map((label) => (
            <Step key={label}>
              <StepLabel>{label}</StepLabel>
            </Step>
          ))}
        </Stepper>

        {/* 步骤内容 */}
        <Box sx={{ minHeight: 400, mb: 4 }}>
          {renderStepContent(activeStep)}
        </Box>

        {/* 操作按钮 */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Button
            onClick={handleBack}
            disabled={activeStep === 0}
            variant="outlined"
          >
            上一步
          </Button>
          
          <Box>
            {activeStep === steps.length - 1 ? (
              <Button
                variant="contained"
                onClick={handleSubmit}
                disabled={loading}
                size="large"
                sx={{
                  background: 'linear-gradient(45deg, #4caf50 30%, #2e7d32 90%)',
                  '&:hover': {
                    background: 'linear-gradient(45deg, #388e3c 30%, #1b5e20 90%)',
                  }
                }}
              >
                {loading ? '创建中...' : '创建内容'}
              </Button>
            ) : (
              <Button
                variant="contained"
                onClick={handleNext}
                disabled={!validateStep(activeStep)}
              >
                下一步
              </Button>
            )}
          </Box>
        </Box>
      </Paper>

      {/* 消息提示 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar(prev => ({ ...prev, open: false }))}
      >
        <Alert
          onClose={() => setSnackbar(prev => ({ ...prev, open: false }))}
          severity={snackbar.severity}
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default Create; 